// Kotlin/Native与Zig的FFI接口实现
// 提供高性能的跨语言互操作机制

const std = @import("std");
const mem = @import("memory.zig");
const caps = @import("caps.zig");
const api = @import("api.zig");
const ui_comm = @import("ui_comm.zig");

// 导出这些函数供Kotlin/Native调用
pub export fn zenrs_zig_init() bool {
    std.log.info("Kotlin/Native Zig FFI initialized", .{});
    return true;
}

// 内存分配函数（供Kotlin/Native使用）
pub export fn zenrs_zig_allocate(size: u64) ?*anyopaque {
    const allocator = std.heap.c_allocator;
    const ptr = allocator.alloc(u8, size) catch return null;
    std.log.info("Allocated {} bytes at {*}", .{size, ptr.ptr});
    return ptr.ptr;
}

// 内存释放函数（供Kotlin/Native使用）
pub export fn zenrs_zig_free(ptr: *anyopaque, size: u64) void {
    if (ptr == @as(?*anyopaque, null)) return;
    const slice = @as([*]u8, @ptrCast(ptr))[0..size];
    std.log.info("Freeing {} bytes at {*}", .{size, ptr});
    std.heap.c_allocator.free(slice);
}

// UI事件结构体
pub const KotlinUIEvent = extern struct {
    event_type: u32,
    x: i32,
    y: i32,
    button_state: u32,
    key_code: u32,
    modifier_state: u32,
    timestamp: u64,
};

// UI命令结构体
pub const KotlinUICommand = extern struct {
    command_id: u32,
    target_id: u64,
    data_size: u32,
    data_ptr: [*]const u8,
};

// 错误码
pub const ZENRS_ERROR_NONE = 0;
pub const ZENRS_ERROR_INVALID_PARAM = 1;
pub const ZENRS_ERROR_NO_MEMORY = 2;
pub const ZENRS_ERROR_NOT_INITIALIZED = 3;
pub const ZENRS_ERROR_NOT_SUPPORTED = 4;

// 创建UI通信通道
pub export fn zenrs_zig_create_ui_channel(
    name: [*]const u8,
    cap_id: u64,
    out_channel_id: *u64
) i32 {
    if (name == @as(?[*]const u8, null) or out_channel_id == @as(?*u64, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    // 转换C字符串为Zig字符串
    const name_str = std.mem.span(@as([*:0]const u8, @ptrCast(name)));
    std.log.info("Creating UI channel: {s}", .{name_str});

    // 获取全局UI通信管理器
    const ui_manager = ui_comm.getGlobalUICommManager();

    // 创建通道
    const result = ui_manager.createChannel(name_str, ui_comm.UIChannelConfig{
        .max_messages = 1024,
        .max_message_size = 4096,
        .shared_memory_size = 1048576,
        .use_zero_copy = false,
        .priority = 1,
    }, @as(api.CapabilityId, @intCast(cap_id))) catch |err| {
        std.log.err("Failed to create UI channel: {s}", .{@errorName(err)});
        return switch (err) {
            error.InsufficientPermissions => ZENRS_ERROR_INVALID_PARAM,
            error.ChannelAlreadyExists => ZENRS_ERROR_INVALID_PARAM,
            error.OutOfMemory => ZENRS_ERROR_NO_MEMORY,
        };
    };

    out_channel_id.* = result;
    std.log.info("UI channel created with ID: {}", .{result});
    return ZENRS_ERROR_NONE;
}

// 发送UI消息
pub export fn zenrs_zig_send_ui_message(
    channel_id: u64,
    message_type: u32,
    sender_id: u64,
    target_id: u64,
    data: [*]const u8,
    data_size: u64
) i32 {
    if (data_size > 0 and data == @as(?[*]const u8, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    // 获取全局UI通信管理器
    const ui_manager = ui_comm.getGlobalUICommManager();

    // 准备数据切片
    const data_slice = if (data_size > 0) data[0..data_size] else "";

    // 发送消息
    const result = ui_manager.sendMessage(
        channel_id,
        message_type,
        sender_id,
        target_id,
        data_slice
    ) catch |err| {
        std.log.err("Failed to send UI message: {s}", .{@errorName(err)});
        return switch (err) {
            error.ChannelNotFound => ZENRS_ERROR_INVALID_PARAM,
            error.MessageTooLarge => ZENRS_ERROR_INVALID_PARAM,
            error.OutOfSharedMemory => ZENRS_ERROR_NO_MEMORY,
        };
    };

    std.log.info("UI message sent successfully, message ID: {}", .{result});
    return ZENRS_ERROR_NONE;
}

// 获取系统状态信息
pub export fn zenrs_zig_get_system_status(
    buffer: [*]u8,
    buffer_size: u64,
    out_actual_size: *u64
) i32 {
    if (buffer == @as(?[*]u8, null) or out_actual_size == @as(?*u64, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    // 准备系统状态信息（JSON格式）
    const system_status = "{" ++
        "\"kernel_version\": \"ZENrs 1.0.0\"," ++
        "\"architecture\": \"exokernel\"," ++
        "\"memory_usage\": {" ++
        "\"total\": 8589934592," ++
        "\"used\": 1073741824," ++
        "\"free\": 7516192768" ++
        "}," ++
        "\"cpu_usage\": 15.5," ++
        "\"running_services\": 8," ++
        "\"ui_channels\": 3" ++
        "}";

    const system_status_bytes = system_status;
    out_actual_size.* = system_status_bytes.len;

    // 检查缓冲区大小
    if (buffer_size >= system_status_bytes.len) {
        @memcpy(buffer[0..system_status_bytes.len], system_status_bytes);
        return ZENRS_ERROR_NONE;
    } else {
        std.log.warn("Buffer too small for system status", .{});
        return ZENRS_ERROR_INVALID_PARAM;
    }
}

// 创建Kuikly专用通道
pub export fn zenrs_zig_create_kuikly_channel(
    name: [*]const u8,
    cap_id: u64,
    out_channel_id: *u64
) i32 {
    if (name == @as(?[*]const u8, null) or out_channel_id == @as(?*u64, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    // 转换C字符串为Zig字符串
    const name_str = std.mem.span(@as([*:0]const u8, @ptrCast(name)));
    std.log.info("Creating Kuikly channel: {s}", .{name_str});

    // 获取全局UI通信管理器
    const ui_manager = ui_comm.getGlobalUICommManager();

    // 创建Kuikly通道
    const result = ui_manager.createKuiklyChannel(name_str, @as(api.CapabilityId, @intCast(cap_id))) catch |err| {
        std.log.err("Failed to create Kuikly channel: {s}", .{@errorName(err)});
        return switch (err) {
            error.InsufficientPermissions => ZENRS_ERROR_INVALID_PARAM,
            error.ChannelAlreadyExists => ZENRS_ERROR_INVALID_PARAM,
            error.OutOfMemory => ZENRS_ERROR_NO_MEMORY,
        };
    };

    out_channel_id.* = result;
    std.log.info("Kuikly channel created with ID: {}", .{result});
    return ZENRS_ERROR_NONE;
}

// 关闭UI通道
pub export fn zenrs_zig_close_ui_channel(channel_id: u64) i32 {
    // 获取全局UI通信管理器
    const ui_manager = ui_comm.getGlobalUICommManager();

    // 关闭通道
    ui_manager.closeChannel(channel_id) catch |err| {
        std.log.err("Failed to close UI channel: {s}", .{@errorName(err)});
        return switch (err) {
            error.ChannelNotFound => ZENRS_ERROR_INVALID_PARAM,
        };
    };

    std.log.info("UI channel closed: {}", .{channel_id});
    return ZENRS_ERROR_NONE;
}

// 获取通道统计信息
pub export fn zenrs_zig_get_channel_stats(
    channel_id: u64,
    out_message_count: *u32,
    out_used_memory: *u64
) i32 {
    if (out_message_count == @as(?*u32, null) or out_used_memory == @as(?*u64, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    // 获取全局UI通信管理器
    const ui_manager = ui_comm.getGlobalUICommManager();

    // 获取统计信息
    if (ui_manager.getChannelStats(channel_id)) |stats| {
        out_message_count.* = stats.message_count;
        out_used_memory.* = stats.used_memory;
        return ZENRS_ERROR_NONE;
    } else {
        std.log.err("Channel not found: {}", .{channel_id});
        return ZENRS_ERROR_INVALID_PARAM;
    }
}

// 转换Kuikly消息格式
pub export fn zenrs_zig_convert_kuikly_message(
    channel_id: u64,
    kuikly_msg: [*]const u8,
    msg_size: u64,
    out_message_id: *u64
) i32 {
    if (kuikly_msg == @as(?[*]const u8, null) or out_message_id == @as(?*u64, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    // 获取全局UI通信管理器
    const ui_manager = ui_comm.getGlobalUICommManager();

    // 准备数据切片
    const msg_slice = kuikly_msg[0..msg_size];

    // 转换消息
    const result = ui_manager.convertKuiklyMessage(channel_id, msg_slice) catch |err| {
        std.log.err("Failed to convert Kuikly message: {s}", .{@errorName(err)});
        return switch (err) {
            error.ChannelNotFound => ZENRS_ERROR_INVALID_PARAM,
            error.InvalidMessageFormat => ZENRS_ERROR_INVALID_PARAM,
            error.OutOfSharedMemory => ZENRS_ERROR_NO_MEMORY,
        };
    };

    out_message_id.* = result.id;
    std.log.info("Kuikly message converted successfully, message ID: {}", .{result.id});
    return ZENRS_ERROR_NONE;
}

// 设置UI组件属性
pub export fn zenrs_zig_set_ui_property(
    component_id: u64,
    property_name: [*]const u8,
    property_value: [*]const u8,
    value_size: u64
) i32 {
    if (property_name == @as(?[*]const u8, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    // 转换C字符串为Zig字符串
    const name_str = std.mem.span(@as([*:0]const u8, @ptrCast(property_name)));
    
    // 转换属性值
    const value_str = if (property_value != @as(?[*]const u8, null) and value_size > 0) 
        property_value[0..value_size]
    else 
        "";

    std.log.info("Setting UI property: component={}, name={s}, value={s}", 
                .{component_id, name_str, value_str});

    // 这里应该实现实际的属性设置逻辑
    return ZENRS_ERROR_NONE;
}

// 获取UI组件属性
pub export fn zenrs_zig_get_ui_property(
    component_id: u64,
    property_name: [*]const u8,
    buffer: [*]u8,
    buffer_size: u64,
    out_actual_size: *u64
) i32 {
    if (property_name == @as(?[*]const u8, null) or buffer == @as(?[*]u8, null) or out_actual_size == @as(?*u64, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    // 转换C字符串为Zig字符串
    const name_str = std.mem.span(@as([*:0]const u8, @ptrCast(property_name)));
    std.log.info("Getting UI property: component={}, name={s}", .{component_id, name_str});

    // 模拟属性值
    const property_value = "simulated_property_value";
    const property_bytes = property_value[0..property_value.len];
    out_actual_size.* = property_bytes.len;

    // 检查缓冲区大小
    if (buffer_size >= property_bytes.len) {
        @memcpy(buffer[0..property_bytes.len], property_bytes);
        return ZENRS_ERROR_NONE;
    } else {
        std.log.warn("Buffer too small for property value", .{});
        return ZENRS_ERROR_INVALID_PARAM;
    }
}

// 创建共享内存区域
pub export fn zenrs_zig_create_shared_memory(
    size: u64,
    name: [*]const u8,
    out_handle: *u64
) i32 {
    if (size == 0 or out_handle == @as(?*u64, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    // 转换C字符串为Zig字符串
    const name_str = if (name != @as(?[*]const u8, null)) std.mem.span(@as([*:0]const u8, @ptrCast(name))) else "";
    std.log.info("Creating shared memory: size={}, name={s}", .{size, name_str});

    // 模拟创建共享内存
    out_handle.* = 123456;
    return ZENRS_ERROR_NONE;
}

// 打开共享内存区域
pub export fn zenrs_zig_open_shared_memory(
    handle: u64,
    out_ptr: *[*]u8,
    out_size: *u64
) i32 {
    if (out_ptr == @as(?*[*]u8, null) or out_size == @as(?*u64, null)) {
        return ZENRS_ERROR_INVALID_PARAM;
    }

    std.log.info("Opening shared memory with handle: {}", .{handle});
    
    // 模拟打开共享内存
    out_ptr.* = @as([*]u8, undefined);
    out_size.* = 0;
    return ZENRS_ERROR_NONE;
}

// 关闭共享内存区域
pub export fn zenrs_zig_close_shared_memory(handle: u64) i32 {
    std.log.info("Closing shared memory with handle: {}", .{handle});
    return ZENRS_ERROR_NONE;
}

// 初始化FFI系统
pub fn init_ffi() !void {
    std.log.info("Initializing Kotlin/Native FFI system", .{});
}

// 清理FFI系统
pub fn deinit_ffi() void {
    std.log.info("Deinitializing Kotlin/Native FFI system", .{});
}